package com.indusfo.spc.controller;

import com.indusfo.spc.pojo.Badpheno;
import com.indusfo.spc.pojo.Dete;
import com.indusfo.spc.pojo.ExcelErrorData;
import com.indusfo.spc.service.DeteService;
import com.indusfo.spc.untlis.ExcelUtil;
import com.indusfo.spc.untlis.GsonUtil;
import com.indusfo.spc.vo.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: DeteController
 * @Description: TODO
 * @author: 余家能
 * @date: 2018/11/26 上午10:45
 */
@Controller
@RequestMapping("/service/Dete")
public class DeteController {

    @Autowired
    private DeteService deteService;

    /*
    查询检测项目
     */
    @RequestMapping(value = "/queryDete")
    @ResponseBody
    public JSONObject queryDete(Dete Dete) {
        JSONObject jsonObject = deteService.listDete(Dete);
        return jsonObject;
    }


    /**
     * 新增/更新检测项目
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/insertDete")
    @ResponseBody
    public JSONObject insertDete(Dete Dete) {
        JSONObject jsonObject = deteService.insertOrUpdateDete(Dete);
        return jsonObject;
    }

    @RequestMapping(value = "/updateDete")
    @ResponseBody
    public JSONObject updateDete(Dete Dete) {
        JSONObject jsonObject = deteService.insertOrUpdateDete(Dete);
        return jsonObject;
    }

    /**
     * 删除/停用/启用检测项目
     *
     * @param deteIds
     * @param dataState
     * @return
     */
    @RequestMapping(value = "/definedDete")
    @ResponseBody
    public JSONObject definesPro(Long[] deteIds, Integer dataState) {
        JSONObject jsonObject = deteService.deleteDete(deteIds, dataState);
        return jsonObject;
    }

    /**
     * @Description: 检测项目删除
     * @Params: [deteIds, dataState]
     * @Returns: com.indusfo.spc.vo.JSONObject
     * @author: 余家能
     * @date: 2018/12/21 下午3:53
     */
    @RequestMapping(value = "/deleteDete")
    @ResponseBody
    public JSONObject delDete(Long[] deteIds, Integer dataState) {
        JSONObject jsonObject = deteService.deleteDete(deteIds, dataState);
        return jsonObject;
    }

    @RequestMapping("/uploadFileDete")
    @ResponseBody
    public JSONObject uploadFileDete(@RequestParam("file") MultipartFile file, Boolean way, HttpServletRequest request, HttpServletResponse response) throws IOException, ParseException {

        //定义一个JSONObject对象用于向前台传输数据
        JSONObject jsonObject = new JSONObject();
        jsonObject.setStatus(JSONObject.SUCCESS);
        //设置错误集合的
        List<ExcelErrorData> errorDatas = new ArrayList<>();
        response.setContentType("text/html;charset=UTF-8");
        //判断上传文件格式是否正确
        Workbook wb = ExcelUtil.getWorkbook(file.getInputStream(), ExcelUtil.isExcel2007(file.getOriginalFilename()));
        if (wb == null) {
            jsonObject.setStatus(JSONObject.ERROR);
            jsonObject.setMsg("文件解析错误");
            errorDatas.add(ExcelErrorData.getExcelErrorData(0, 0, "文件解析错误"));
        } else {
            //获取excel文件的第一个sheet
            Sheet sheet = wb.getSheetAt(0);
            if (sheet == null) {
                jsonObject.setStatus(JSONObject.ERROR);
                jsonObject.setMsg("未找到需要导入的表格");
                errorDatas.add(ExcelErrorData.getExcelErrorData(0, 0, "未找到需要导入的表格"));
            } else {
                //获取最后一行的行号
                int rowCount = sheet.getLastRowNum();
                if (rowCount < 1) {
                    jsonObject.setStatus(JSONObject.ERROR);
                    jsonObject.setMsg("未找到需要导入的数据，请确认表格是否保存！！！");
                    errorDatas.add(ExcelErrorData.getExcelErrorData(0, "未找到需要导入的数据，请确认表格是否保存！！！"));
                } else {
                    List<Dete> addProductPlans = new ArrayList<>();
                    for (int i = 1; i <= rowCount; i++) {
                        boolean needAdd = true;
                        //获取到每一行的每一列的数据
                        //检测项目编码
                        String vcDetej = com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, i, 0, false);
                        //检测项目名称
                        String vcDeteName = com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, i, 1, false);
                        //仪器类型
                        String lInsTypeName = com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, i, 2, false);
                        //单位
                        String lDeteUnitName = com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, i, 3, false);
                        //采集类型
                        String gatherTypeName = com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, i, 4, false);
                        //项目类型
                        String projectTypeName = com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, i, 5, false);
                        //是否上报异常
                        String errUploadName = com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, i, 6, false);
                        //不良现象名称
                        String badphenoName = com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, i, 7, false);
                        Dete plan = new Dete(vcDetej, vcDeteName, lDeteUnitName, lInsTypeName, projectTypeName, gatherTypeName, errUploadName, badphenoName);
                        int m = i + 1;
                        //将excel中的每一行数据存储进行检查
                        String result = deteService.checkNoRepeat(plan);
                        if (result != null) {
                            errorDatas.add(ExcelErrorData.getExcelErrorData(i, result));
                            needAdd = false;
                        }
                        for (int j = 1; j < i; j++) {
                            //判断检测项目编码
                            String oldvcDetej = StringUtils.trimToEmpty(com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, j, 0, false)).replaceAll("\\s*", "");
                            if (!StringUtils.isBlank(vcDetej) && !StringUtils.isBlank(oldvcDetej) && oldvcDetej.equals(vcDetej)) {
                                needAdd = false;
                                errorDatas.add(ExcelErrorData.getExcelErrorData(i, "与表格中第" + j + "行存在相同控制项目编码"));
                            }
                        }
                        if (needAdd) {
                            addProductPlans.add(plan);
                        } else {
                            jsonObject.setStatus(JSONObject.ERROR);
                            jsonObject.setMsg("导入数据中存在异常信息");
                        }

                    }
                    //根据这些来判断是否是中止导入还是跳过继续进行导入
                    if (jsonObject.getStatus().equals(JSONObject.ERROR) && !way) {
                        jsonObject.setMsg(jsonObject.getMsg() + ",中止导入");
                    } else {
                        if (addProductPlans.size() > 0) {
                            try {
                                deteService.updateListDete(addProductPlans);
                                //当程序执行到这里时,判断信息是否为空为空的话设置导入成功
                                jsonObject.setMsg(StringUtils.isBlank(jsonObject.getMsg()) ? "导入成功" : jsonObject.getMsg());
                                if ("导入成功".equals(jsonObject.getMsg())) {
                                    jsonObject.setStatus(JSONObject.SUCCESS);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                jsonObject.setMsg("导入失败");
                            }
                        }
                    }
                    //msg.setData(GsonUtil.toJson(errorDatas));
                }
            }
        }
        jsonObject.setData(GsonUtil.toJson(errorDatas));

        return JSONObject.build(jsonObject.getStatus(), jsonObject.getMsg(), errorDatas);
    }


    /**
     * 去添加查询（产品，任务单，批次）
     */
    @RequestMapping(value = "/queryListDeteToInsert")
    @ResponseBody
    public JSONObject queryListDeteToInsert(Dete dete) {
        JSONObject json = deteService.queryListDeteToInsert(dete);
        return json;
    }

}
